/*
*   @FileName   :   stm32_spi.h
*
*   @Date       :   25-8-3
*
*   @Brief      :   使用stm32固件库来开发基于可重入的spi总线驱动
*
*   @Author     :   ZzlYanG
*
*   @ModifyDate :
*
*/


#ifndef STM32_SPI_H_
#define STM32_SPI_H_
#include "stm32f10x.h"

#define  SPI_CH_Max 2
/*
 *SPI 设备通道数量
 */
typedef enum {
    SPI_CH1,
    SPI_CH2
}SPI_CH_Type;
// SPI配置结构体
typedef struct {
    uint16_t mode;          // SPI工作模式主机或从机
    uint16_t direction;     // SPI_Direction_2Lines_FullDuplex, etc.
    uint16_t data_size;     // SPI_DataSize_8b or SPI_DataSize_16b
    uint16_t cpol;          // SPI_CPOL_Low or SPI_CPOL_High
    uint16_t cpha;          // SPI_CPHA_1Edge or SPI_CPHA_2Edge
    uint16_t nss;           // SPI_NSS_Soft or SPI_NSS_Hard
    uint16_t baudrate_prescaler; // SPI_BaudRatePrescaler_2 to _256
    uint16_t first_bit;     // SPI_FirstBit_MSB or SPI_FirstBit_LSB
} SPI_Config;

// SPI设备句柄
typedef struct {
    SPI_TypeDef* instance;
    SPI_Config config;
    volatile bool locked;
    GPIO_TypeDef* cs_port;
    uint16_t cs_pin;

} SPI_Handle;


// 初始化函数
void SPI_InitHandle(SPI_CH_Type Ch,SPI_Handle *hspi, SPI_Interface interface, const SPI_Config *config, GPIO_TypeDef* cs_port, uint16_t cs_pin);

// 基础功能函数
bool SPI_Lock(SPI_Handle *hspi, uint32_t timeout);
void SPI_Unlock(SPI_Handle *hspi);
bool SPI_TransmitReceive(SPI_Handle *hspi, uint8_t *tx_data, uint8_t *rx_data, uint16_t size, uint32_t timeout);
bool SPI_Transmit(SPI_Handle *hspi, uint8_t *data, uint16_t size, uint32_t timeout);
bool SPI_Receive(SPI_Handle *hspi, uint8_t *buffer, uint16_t size, uint32_t timeout);

// 高级功能函数
bool SPI_WriteRegister(SPI_Handle *hspi, uint8_t reg, uint8_t value, uint32_t timeout);
bool SPI_ReadRegister(SPI_Handle *hspi, uint8_t reg, uint8_t *value, uint32_t timeout);
bool SPI_BurstWrite(SPI_Handle *hspi, uint8_t start_reg, uint8_t *values, uint16_t count, uint32_t timeout);
bool SPI_BurstRead(SPI_Handle *hspi, uint8_t start_reg, uint8_t *buffer, uint16_t count, uint32_t timeout);


#endif //INC_2_1_STM32工程模板_STM32_SPI_H

